package com.rzico.sbl.ui.order

import android.text.Editable
import android.text.InputFilter
import android.text.TextWatcher
import android.widget.EditText
import android.widget.ImageView
import androidx.core.view.isGone
import androidx.core.view.isInvisible
import androidx.core.view.isVisible
import com.bumptech.glide.Glide
import com.google.gson.Gson
import com.jeremyliao.liveeventbus.LiveEventBus
import com.jeremyliao.liveeventbus.utils.observe
import com.luck.picture.lib.config.SelectModeConfig
import com.luck.picture.lib.entity.LocalMedia
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityDeliverDispatchBinding
import com.rzico.sbl.model.BaseUrl
import com.rzico.sbl.model.CommonData
import com.rzico.sbl.other.privacyStatus
import com.rzico.sbl.other.userRole
import com.rzico.sbl.picture.buildSelectionModel
import com.rzico.sbl.picture.callback
import com.rzico.sbl.ui.member.MemberBucketActivity
import com.rzico.sbl.ui.member.MemberDetailActivity
import com.rzico.sbl.ui.member.MemberTicketActivity
import com.rzico.sbl.viewmodel.DeliverViewModel
import com.xinnuo.common.decoration.DividerLRDecoration
import com.xinnuo.common.extend.*
import com.xinnuo.common.helper.*
import com.xinnuo.common.listener._TextWatcher
import com.xinnuo.common.other.DecimalNumberFilter
import com.xinnuo.common.view.FullyGridLayoutManager
import com.xinnuo.common.view.FullyLinearLayoutManager
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.glideExt.loadCircleImage
import com.xinnuo.common_ui.glideExt.loadRoundedImage
import com.xinnuo.common_ui.oss.OSSHelper
import com.xinnuo.common_ui.utils.bindLifeCycle
import com.xinnuo.common_ui.utils.clear
import com.xinnuo.common_ui.utils.showActionDialog
import com.xinnuo.common_ui.utils.showBottomPhoneDialog
import com.xinnuo.common_ui.utils.showListDialog
import com.xinnuo.common_ui.utils.subscribeBySuccess
import com.xinnuo.slimadapter.SlimAdapter
import net.mikaelzero.mojito.ext.mojito
import org.json.JSONObject

class DeliverDispatchActivity : BaseActivity(R.layout.activity_deliver_dispatch) {

    private val mBinding by lazy { ActivityDeliverDispatchBinding.bind(getRootView()) }

    // 品牌列表
    private val mBarrelList = ArrayList<CommonData>()

    // 付款方式列表
    private val mPayList = ArrayList<CommonData>()

    // 图片列表
    private val mPhotoList = ArrayList<LocalMedia>()

    // 会员信息
    private var mCardId = ""        //会员卡ID
    private var mMemberId = ""      //会员ID
    private var mReceivePhone = ""  //收货电话
    private var mReceiveAdress = "" //收货地址

    private var mOrderMethod = "" //订单类型：线上(online)、报单(offline)
    private var mPayStatus = ""   //付款状态
    private var mPayMethod = ""   //付款方式
    private var mAmountPaid = ""  //实收金额
    private var mPaperPaid = ""   //实收水票
    private var mSignature = ""   //电子签名
    private var mLevel = -1       //楼层
    private var barrelPhoto = ""   //还桶
    private var ishtimg=false

    override fun getViewModel() = get<DeliverViewModel>()

    override fun initData() {
        initTitle(title = "送达")

        initLayout()
        initPhotoLayout()

        // 空桶品牌
        getViewModel()
            .getBarrelList(
                intent.getExtra("shipId")
            )

        getData()
    }

    private fun initLayout() {
        mBinding
            .recycleList
            .apply {
                isNestedScrollingEnabled = false
                layoutManager = FullyLinearLayoutManager(getIContext())

                addItemDecoration(
                    DividerLRDecoration(
                        spaceL = 0f,
                        spaceR = 0f,
                        hasFooter = false
                    )
                )

                mAdapter = SlimAdapter.creator()
                    .register<CommonData>(R.layout.item_dispatch_list) { jector, bean, index ->
                        jector.apply {
                            text(R.id.item_patch_name, bean.name)
                            text(R.id.item_patch_buy, bean.hangQuantity)
                            text(R.id.item_patch_send, bean.quantity)

                            visibility(R.id.item_patch_del, goneValue { bean.show })
                            visibility(R.id.item_patch_arrow, goneValue { bean.show })
                            visibility(R.id.item_patch_layout1, visibleValue { bean.show })
                            visibility(R.id.item_patch_layout2, goneValue { bean.show })
                            visibility(
                                R.id.item_patch_layout3,
                                visibleValue { bean.hangQuantity.intValue > 0 }
                            )

                            with<EditText>(R.id.item_patch_back) {
                                if (it.tag != null && it.tag is TextWatcher) {
                                    it.removeTextChangedListener(it.tag as TextWatcher)
                                }

                                it.setText(bean.returnQuantity)
                                it.setSelection(it.text.length)

                                val textWatcher = object : _TextWatcher() {
                                    override fun afterTextChanged(s: Editable) {
                                        bean.returnQuantity = s.toString()
                                        if (index==0&&s.toInt!=bean.quantity.toInt){
                                            ishtimg=true
                                            mBinding.rlthmsg.visible()
                                        }else{
                                            ishtimg=false
                                            mBinding.rlthmsg.gone()
                                        }

                                    }
                                }
                                it.addTextChangedListener(textWatcher)
                                it.tag = textWatcher
                            }

                            with<EditText>(R.id.item_patch_num) {
                                if (it.tag != null && it.tag is TextWatcher) {
                                    it.removeTextChangedListener(it.tag as TextWatcher)
                                }

                                it.setText(bean.returnQuantity)
                                it.setSelection(it.text.length)

                                val textWatcher = object : _TextWatcher() {
                                    override fun afterTextChanged(s: Editable) {
                                        bean.returnQuantity = s.toString()
                                    }
                                }
                                it.addTextChangedListener(textWatcher)
                                it.tag = textWatcher
                            }

                            clicked(R.id.item_patch_fl) { if (!bean.show) showLoopDialog(index) }
                            clicked(R.id.item_patch_del) {
                                mList.removeAt(index)
                                mAdapter.apply {
                                    notifyItemRemoved(index)
                                    notifyItemRangeChanged(index, mList.size - index)
                                }
                            }
                        }
                    }
                    .attachTo(this)
            }
    }

    private fun initPhotoLayout() {
        mBinding.apply {
            photoList.also { layout ->
                layout.isNestedScrollingEnabled = false
                layout.layoutManager = FullyGridLayoutManager(baseContext, 3)
                layout.adapter = SlimAdapter.creator()
                    .register<LocalMedia>(R.layout.item_photo_grid) { jector, bean, _ ->
                        jector.apply {
                            visibility(
                                R.id.item_photo_del,
                                goneValue { bean.compressPath.isEmpty() }
                            )

                            with<ImageView>(R.id.item_photo_img) {
                                bean.compressPath
                                    .isNotEmpty()
                                    .conditionElse(
                                        actionTrue = {
                                            it.loadRoundedImage(
                                                url = bean.compressPath,
                                                radius = 10f
                                            )
                                        },
                                        actionFalse = {
                                            it.setImageResource(R.mipmap.icon_photo01)
                                        }
                                    )
                            }

                            clicked(R.id.item_photo_del) {
                                mPhotoList.remove(bean)

                                if (mPhotoList.size < 3
                                    && mPhotoList.none { it.compressPath.isEmpty() }
                                )
                                    mPhotoList.add(LocalMedia().apply { compressPath = "" })

                                notifyDataSetChanged()
                            }

                            clicked {
                                bean.compressPath.ifEmpty { openGallery(3) }
                            }
                        }
                    }
                    .attachTo(layout)
            }

            mPhotoList.add(LocalMedia().apply { compressPath = "" })
            (photoList.adapter as SlimAdapter).setDataList(mPhotoList)
        }
    }

    override fun initListener() {
        mBinding.apply {
            dispatchReal.filters = arrayOf(
                DecimalNumberFilter(),
                InputFilter.LengthFilter(8)
            )

            btAdd.oneClick {
                mBarrelList
                    .isEmpty()
                    .condition {
                        showToast("获取商品信息失败！")
                        return@oneClick
                    }

                showLoopDialog()
            }

            dispatchCall.oneClick {
                mReceivePhone.notEmpty {
                    showBottomPhoneDialog(this)
                }
            }
            htphotoimg.oneClick {
                opemhtimg()
            }
            dispatchAddrCopy.oneClick {
                copyStringToClip(
                    "${dispatchName.textTrim}\n$mReceiveAdress"
                )
                showToast("复制成功！")
            }

            dispatchMember.oneClick {
                startActivityEx<MemberDetailActivity>(
                    "cardId" to mCardId,
                    "memberId" to mMemberId
                )
            }

            dispatchBarrelLl.oneClick {
                mCardId.notEmpty {
                    startActivityEx<MemberBucketActivity>(
                        "cardId" to mCardId,
                        "memberId" to mMemberId
                    )
                }
            }

            dispatchPaperLl.oneClick {
                mCardId.notEmpty {
                    startActivityEx<MemberTicketActivity>(
                        "cardId" to mCardId,
                        "memberId" to mMemberId
                    )
                }
            }

            dispatchUnpayLl.oneClick {
                mPayList
                    .isNotEmpty()
                    .conditionElse(
                        actionTrue = ::showActionDialog,
                        actionFalse = {
                            getViewModel().getPayment()
                        }
                    )
            }

            dispatchSignLl.oneClick {
                startActivityEx<DeliverSignatureActivity>()
            }

            dispatchFloorLl.oneClick {
                val items = arrayListOf(
                    "有电梯", "1层", "2层", "3层", "4层",
                    "5层", "6层", "7层", "8层", "9层"
                )

                showListDialog(
                    title = "请选择楼层",
                    items = items,
                    index = items.indexOf(dispatchFloor.content),
                    listener = { index, hint ->
                        mLevel = index
                        dispatchFloor.text = hint
                    }
                )
            }

            btDeliver.oneClick {
                mMemberId
                    .isEmpty()
                    .condition {
                        showToast("获取会员信息失败")
                        return@oneClick
                    }

                (dispatchMethodLl.isVisible
                        && mPayMethod.isEmpty())
                    .condition {
                        showToast("请选择付款方式")
                        return@oneClick
                    }

                (mPayMethod == "exchange"
                        && dispatchPage.content.isEmpty())
                    .condition {
                        showToast("请输入实收纸质水票")
                        return@oneClick
                    }

                (dispatchRealLl.isVisible
                        && mPayMethod != "exchange"
                        && dispatchReal.content.isEmpty())
                    .condition {
                        showToast("请输入实收金额")
                        return@oneClick
                    }
                (ishtimg
                        && barrelPhoto .isEmpty())
                    .condition {
                        showToast("请上传还桶照片")
                        return@oneClick
                    }

                mList.forEach {
                    it as CommonData
                    it.returnQuantity
                        .isEmpty()
                        .condition {
                            it.returnQuantity = "0"
                        }
                }

                getViewModel()
                    .deliveryOrder(
                        "sn" to intent.getExtra("shippingSn"),
                        "payStatus" to "paid",
                        "payMethod" to mPayMethod,
                        "amountPaid" to conditionIf(
                            dispatchRealLl.isVisible,
                            dispatchReal.content,
                            mAmountPaid
                        ),
                        "paperPaid" to conditionIf(
                            dispatchPageLl.isVisible,
                            dispatchPage.content,
                            mPaperPaid
                        ),
                        "level" to mLevel,
                        "memo" to dispatchMemo.content,
                        "signature" to mSignature,
                        "body" to Gson().toJson(mList),
                        "photos" to if (mPhotoList.any { it.compressPath.isNotEmpty() }) {
                            Gson().toJson(
                                mPhotoList
                                    .filterNot { it.compressPath.isEmpty() }
                                    .map { it.compressPath }
                            )
                        } else "[]",
                        "barrelPhoto" to barrelPhoto

                    )
                    .bindLifeCycle(getLifecycleOwner())
                    .subscribeBySuccess(
                        event = getViewModel(),
                        onSuccess = {
                            showToast("确认送达成功！")

                            // 更新运单列表
                            LiveEventBus
                                .get("deliverList")
                                .post("refresh")

                            // 更新批量运单列表
                            LiveEventBus
                                .get("batchList")
                                .post("refresh")

                            // 更新运单详情
                            LiveEventBus
                                .get("deliverDetail")
                                .post("refresh")

                            finishView()
                        }
                    )
            }
        }

        // 观察空桶品牌
        getViewModel()
            .mBarrelEvent
            .observe(this) { value ->
                mBarrelList.clear()
                mBarrelList.addItems(value)

                mList.clear()
                mList.addItems(value.filter { it.show })

                mAdapter.setDataList(mList)
            }

        // 观察电子水票
        getViewModel()
            .mTicketEvent
            .observe(this) {
                mBinding
                    .dispatchPaper
                    .text = it.toString()
            }

        // 观察支付方式
        getViewModel()
            .mPayEvent
            .observe(getLifecycleOwner()) {
                mPayList.addItems(it)
                showActionDialog()
            }

        // 电子签单监听
        observe<String>("signature") {
            mSignature = it

            Glide.with(getIContext())
                .load(it)
                .into(mBinding.dispatchSign)
        }
    }

    /**
     * 回桶品牌
     */
    private fun showLoopDialog(position: Int = -1) {
        val items =
            mBarrelList
                .filter {
                    mList.none { item ->
                        (item as CommonData).id == it.id
                    }
                }

        items.notEmpty {
            showListDialog(
                title = "请选择品牌",
                items = map { it.name.orEmpty() },
                listener = { index, _ ->
                    if (position > -1) {
                        mList.removeAt(position)
                        mList.add(position, items[index])
                        mAdapter.notifyDataSetChanged()
                    } else {
                        mList.add(items[index])
                        mAdapter.notifyDataSetChanged()
                    }
                }
            )
        }
    }

    /**
     * 付款方式
     */
    private fun showActionDialog() {
        val items =
            mPayList
                .map { it.name.orEmpty() }
                .toTypedArray()

        showActionDialog(*items) { index, hint ->
            mPayMethod = mPayList[index].id

            mBinding.apply {
                dispatchUnpay.text = hint
                mSignature = ""
                dispatchPage.clear()
                dispatchReal.clear()

                dispatchPageLl.isVisible = mPayMethod == "exchange"
                dispatchSignLl.isVisible = mPayMethod == "signature"
                dispatchRealLl.isVisible =
                    mPayMethod == "exchange"
                            || mPayMethod == "cash"
                            || mPayMethod == "weixin"
                            || mPayMethod == "ali"
                dispatchRealStar.isInvisible = mPayMethod == "exchange"

                when (mPayMethod) {
                    "exchange" -> {
                        val quantitySum = mList.sumOf {
                            it as CommonData
                            it.quantity.intValue
                        }

                        dispatchPage.setText(quantitySum.toString())
                        dispatchPage.setSelection(dispatchPage.text.length)
                    }

                    "cash", "weixin", "ali" -> {
                        dispatchReal.setText(dispatchAmount.content)
                        dispatchReal.setSelection(dispatchReal.text.length)
                    }
                }
            }
        }
    }

    /**
     * 选择图片
     */
    private fun openGallery(maxSelectNum: Int) {
        buildSelectionModel(
            selectMode = SelectModeConfig.MULTIPLE,
            maxSelectNum = maxSelectNum,
            isCropEnable = false,
            isMarkEnable = true,
            selectList = mPhotoList.filter { it.compressPath.isNotEmpty() }
        ).callback {
            onResult { list ->
                list.notEmpty {
                    mPhotoList.clear()

                    OSSHelper
                        .manager
                        .uploadImages(
                            prefix = "dispatch",
                            pathList = map { it.watermarkPath },
                            onBefore = { showLoading("正在上传中...") },
                            onAfter = { dismissLoading() },
                            onNext = { index, result ->
                                mPhotoList.add(
                                    this[index].apply {
                                        compressPath = result.responseHeader["url"].orEmpty()
                                        watermarkPath = realPath
                                    }
                                )
                            },
                            onFinish = {
                                (mPhotoList.size < 3)
                                    .condition {
                                        mPhotoList.add(
                                            LocalMedia()
                                                .apply { compressPath = "" }
                                        )
                                    }

                                (mBinding.photoList.adapter as SlimAdapter).notifyDataSetChanged()
                            },
                            onException = { showToast("网络异常，请稍候再试！") }
                        )
                }
            }
        }
    }
    private fun opemhtimg(){
        buildSelectionModel( isCropEnable = false,
            isMarkEnable = true)
            .callback {
                onResult {
                    it.notEmpty {
                        val media = this.first()
                        barrelPhoto=""
                        OSSHelper
                            .manager
                            .uploadSingleImage(
                                path = media.watermarkPath ,
                                onBefore = { showLoading("正在上传中...") },
                                onAfter = { dismissLoading() },
                                onSuccess = { result ->
                                    barrelPhoto = result.responseHeader["url"].orEmpty()
                                    mBinding
                                        .htphotoimg
                                        .loadRoundedImage(
                                            media.watermarkPath
                                        )

                                },
                                onError = {exception ->  showToast("网络异常，请稍候再试！") }
                            )
                    }
                }
            }
    }

    /**
     * 运单详情
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .viewBarrel(intent.getExtra("shippingSn"))
            .bindLifeCycle(getLifecycleOwner())
            .subscribeBySuccess(
                event = getViewModel(),
                onSuccess = { json ->
                    val obj = JSONObject(json)

                    mCardId = obj.optNotNull("cardId")
                    mMemberId = obj.optNotNull("memberId")
                    mPayStatus = obj.optNotNull("payStatus")
                    mOrderMethod = obj.optNotNull("orderMethod")
                    mAmountPaid = obj.optNotNull("amountPaid")
                    mPaperPaid = obj.optNotNull("paperPaid")
                    val sellerId = obj.optNotNull("sellerId")
                    val shopOwnerId = obj.optNotNull("shopOwnerId")

                    mBinding.apply {
                        /*---------------------- 客户信息 ----------------------*/
                        val objReceive = obj.optJSONObject("receiver") ?: JSONObject()
                        mReceivePhone = objReceive.optNotNull("phone")
                        mReceiveAdress = objReceive.optNotNull("areaName")
                        mReceiveAdress += objReceive.optNotNull("address")

                        // 姓名电话
                        dispatchName.text = "${objReceive.optNotNull("consignee")}  ${
                            when {
                                userRole in "1,2"
                                        || privacyStatus == "off" -> mReceivePhone

                                else -> mReceivePhone.phoneReplaceWithStar()
                            }
                        }"
                        // 收货地址
                        dispatchAddr.text = mReceiveAdress
                        // 会员详情
                        dispatchMember.isVisible =
                            userRole in "1,2"
                                    && mCardId.isNotEmpty()
                                    && mMemberId.isNotEmpty()
                        // 历史欠款
                        dispatchBefore.text = obj.optNotNull("arrears").formatDecimal()
                        // 历史借桶
                        dispatchBarrel.text = obj.optNotEmpty("borrow", "0")
                        // 买家留言
                        dispatchMai.text =
                            obj.optNotNull("orderMemo")
                                .notEmpty { dispatchMaiLl.visible() }
                        // 商家备注
                        dispatchCmemo.text =
                            obj.optNotNull("cardMemo")
                                .notEmpty { dispatchCmemoLl.visible() }

                        /*---------------------- 订单信息 ----------------------*/
                        // 订单编号
                        dispatchNum.text = obj.optNotNull("orderSn")
                        // 订单类型
                        dispatchType.text = when (mOrderMethod) {
                            "online" ->
                                when (obj.optNotNull("paymentPluginId")) {
                                    "ticketPayPlugin" -> "货到付款"
                                    else -> "线上订单"
                                }

                            "ali" ->
                                when (obj.optNotNull("paymentPluginId")) {
                                    "ticketPayPlugin" -> "货到付款"
                                    else -> "支付宝"
                                }

                            "offline" -> "人工报单"
                            "history" -> "人工补单"
                            "nongfu" -> "农夫APP"
                            "meituan" -> "美团"
                            "eleme", "elemengc" -> "饿了么"
                            "jd" -> "京东"
                            "taobao" -> "淘宝"
                            "pinduoduo" -> "拼多多"
                            else -> "其他"
                        }
                        // 支付方式
                        dispatchPay.text =
                            obj.optNotNull("payMethodName")
                                .also {
                                    dispatchPayLl.isGone = it.isEmpty()
                                }
                        // 支付状态
                        dispatchMethod.text =
                            when (mOrderMethod) {
                                "offline" ->
                                    obj.optNotNull("payStatus")
                                        .run {
                                            when (this) {
                                                "unpaid" -> {
                                                    obj.optNotNull("payMethod")
                                                        .run {
                                                            isEmpty()
                                                                .conditionElseValue(
                                                                    actionTrue = {
                                                                        dispatchMethodLl.visible()
                                                                        dispatchUnpayLl.visible()
                                                                        "未支付"
                                                                    },
                                                                    actionFalse = { "已支付" }
                                                                )
                                                        }
                                                }

                                                else -> "已支付"
                                            }
                                        }

                                "online", "ali" ->
                                    obj.optNotNull("payStatus")
                                        .run {
                                            when (this) {
                                                "unpaid" -> {
                                                    dispatchMethodLl.visible()
                                                    dispatchUnpayLl.visible()
                                                    "未支付"
                                                }

                                                else -> "已支付"
                                            }
                                        }

                                else -> "已支付"
                            }
                        // 应收/结算金额
                        (sellerId == shopOwnerId)
                            .conditionElse(
                                actionTrue = {
                                    dispatchHint.text = "应收金额"
                                    dispatchAmount.text =
                                        obj.optNotNull("amountPayable")
                                            .also {
                                                dispatchAmountLl.isVisible =
                                                    dispatchMethodLl.isVisible
                                            }
                                            .formatDecimal()
                                },
                                actionFalse = {
                                    dispatchHint.text = "结算金额"
                                    dispatchAmount.text =
                                        obj.optNotNull("settlementPrice")
                                            .also {
                                                dispatchAmountLl.isVisible = it.doubleValue > 0.0
                                            }.formatDecimal()
                                }
                            )
                        // 派单留言
                        dispatchPai.text =
                            obj.optNotNull("memo")
                                .trimEnd('\n')
                                .notEmpty { dispatchPaiLl.visible() }

                        /*---------------------- 配送信息 ----------------------*/
                        // 客户楼层
                        mLevel = objReceive.optInt("level")
                        dispatchFloor.text = if (mLevel == 0) "有电梯" else "${mLevel}层"
                    }

                    // 电子水票
                    mCardId.notEmpty {
                        getViewModel().ticketCount(this)
                    }
                }
            )
    }

}